package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.model.MaoYanMovieBasicInfoModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
@Component("MaoYanMovieSupplementBasicInfoPeoplePageProcessor")
public class MaoYanMovieSupplementBasicInfoPeoplePageProcessor extends AUrlPageProcessor {
	
	
	private String request_url = "https://piaofang.maoyan.com/movie/%s/celebritylist";
	
    @Autowired
    private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;
    
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
            case "/celebritylist":
            	this.basicinfoPeoplelistProcess(page,extrasMap);
            	break;
            default:
                this.addRequestProcess(page);
                break;
        }
		
	}
	
	//人员相关
	private void basicinfoPeoplelistProcess(Page page, Map<String, Object> extrasMap) {
		String url = page.getRequest().getUrl();
		String dataId = extrasMap.get("dataId").toString();
		String tvname = extrasMap.get("movieName").toString();
		if(url.contains(dataId)){
			MaoYanMovieBasicInfoModel maoYanMovieBasicInfoModel = new MaoYanMovieBasicInfoModel();
			maoYanMovieBasicInfoModel.setDataid(dataId);
			maoYanMovieBasicInfoModel.setId(dataId);
			maoYanMovieBasicInfoModel.setTvname(tvname);
			List<String> dlTagAll = page.getHtml().xpath("//div[@class='sticky-container']//div[@class='scroller cat-wrapper']//div[@class='wrapper cat-content']"
					+ "//div[@class='panel-wrapper']//dl").all();
			for(String dl : dlTagAll){
				Map<String,Object> result = convertPeopleRelateInfo(new Html(dl));
				if(result.get("flag").equals("导演")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setDirector(nameArr);
					maoYanMovieBasicInfoModel.setDirectorEnglishName(engNameArr);
				}
				else if(result.get("flag").equals("演员")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					String [] roleArr = ((String [][])result.get("nameAndEngNameAndRole"))[2];
					maoYanMovieBasicInfoModel.setActor(nameArr);
					maoYanMovieBasicInfoModel.setActorEnglishName(engNameArr);
					maoYanMovieBasicInfoModel.setActorRole(roleArr);
				}
				else if(result.get("flag").equals("编剧")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setScreenWriter(nameArr);
					maoYanMovieBasicInfoModel.setScreenwriterEnglishName(engNameArr);
				}
				else if(result.get("flag").equals("制片人")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setProducer(nameArr);
					maoYanMovieBasicInfoModel.setProducerEnglishName(engNameArr);
				}
				else if(result.get("flag").equals("摄影师")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setPhotographer(nameArr);
					maoYanMovieBasicInfoModel.setPhotographerEnglishName(engNameArr);
				}
				else if(result.get("flag").equals("出品人")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setPublisher(nameArr);
					maoYanMovieBasicInfoModel.setPublisherEnglishName(engNameArr);
				}
				else if(result.get("flag").equals("发行")){
					String [] nameArr = ((String [][])result.get("nameAndEngNameAndRole"))[0];
					String [] engNameArr = ((String [][])result.get("nameAndEngNameAndRole"))[1];
					maoYanMovieBasicInfoModel.setIssuer(nameArr);
					maoYanMovieBasicInfoModel.setIssuerEnglishName(engNameArr);
				}
			}
			//保存
			page.putField(MaoYanMovieBasicInfoModel.class.getName(), maoYanMovieBasicInfoModel);
		}
		
	}
	
	private Map<String,Object> convertPeopleRelateInfo(Html dlHtml){
		
		Map<String,Object> result = new HashMap<String,Object>();
		
		String title = dlHtml.xpath("//dl[@class='panel-main category']//dt[@class='panel-header sticky-wrapper']//span[@class='title-name']//text()").get();
		List<String> contentAll = dlHtml.xpath("//dl[@class='panel-main category']//dd[@class='panel-content']//div[@class='p-item']").all();
		String[][] nameAndEngNameAndRole = new String[3][];
		int size = contentAll.size()<=10?contentAll.size():10;
		String [] nameArr = new String[size]; 
		String [] engNameArr = new String[size];
		String [] roleArr = new String[size];
		if(title.equals("导演") || title.equals("演员") || title.equals("编剧")
				|| title.equals("制片人") || title.equals("摄影师")
				|| title.equals("出品人") || title.equals("发行")){
			for(int i=0;i<size;i++){
				String name = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
						+ "//p[@class='p-item-name ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
								+ "//p[@class='p-item-name ellipsis-1']//text()").get();
				String engName = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
						+ "//p[@class='p-item-e-name ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
								+ "//p[@class='p-item-e-name ellipsis-1']//text()").get();
				String role = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
						+ "//p[@class='p-item-play ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
								+ "//p[@class='p-item-play ellipsis-1']//text()").get().replace("饰：", "").replace("（配音）", "");
				nameArr[i] = name.replaceAll("[\"]", "").replace(",", "/");
				engNameArr[i] = engName.replaceAll("[\"]", "").replace(",", "/");
				roleArr[i] = role.replaceAll("[\"]", "").replace(",", "/");
			}
			for(int j=0;j<nameArr.length;j++){
				if(StringUtils.isNotEmpty(nameArr[j])){
					nameAndEngNameAndRole[0] = nameArr;
				}
				if(StringUtils.isNotEmpty(engNameArr[j])){
					nameAndEngNameAndRole[1] = engNameArr;
				}
				if(StringUtils.isNotEmpty(roleArr[j])){
					nameAndEngNameAndRole[2] = roleArr;
				}
			}
			
		}
		result.put("nameAndEngNameAndRole", nameAndEngNameAndRole);
		result.put("flag", title);
		return result;
	}
		
	public void addRequestProcess(Page page){
		List<Map<String, Object>> movList = customParam();
        movList.forEach(movMap ->
        {
            String dataId = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, StringUtil
                    .nullToString(movMap.get("dataid")));
            if (StringUtils.isEmpty(dataId))
                return;
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("dataId", dataId);
            paramMap.put("movieName", StringUtil.nullToString(movMap.get("tvname")));
			PageUtils.addTargetRequest(page, String.format(request_url, dataId), paramMap);
        });
	}
	
	
	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{"https://www.baidu.com/"};
	}

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/celebritylist")){
			return "/celebritylist";
		}
        return Constants.PageDataType.SEARCH_LIST;
	}

	//获取数据列表
	private List<Map<String, Object>> customParam(){
		return maoYanMovieBasicInfoService.queryMovieBasicInfoList();
	}
	
	
	public static void main(String[] args) {
//		String[] arr = matchShowingAreaAndShowingDate("2019中国大陆");
//		System.out.println(arr[0]);
//		System.out.println(arr[1]);
		
	}
	
	
}
